package com.ny.zmb.openapi.controller;

import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.mzlion.easyokhttp.HttpClient;
import com.ny.zmb.openapi.constant.PHPConstant;
import com.ny.zmb.openapi.controller.entity.Result;
import com.ny.zmb.openapi.entity.PmProductOrder;
import com.ny.zmb.openapi.mapper.PmProductOrderMapper;
import com.ny.zmb.openapi.util.StringUtil;
import com.ny.zmb.openapi.ysutil.YsHttpUtil;
import com.ny.zmb.openapi.ysutil.base.EYinShengBase;
import com.ny.zmb.openapi.ysutil.common.ServiceEnum;
import com.ny.zmb.openapi.ysutil.common.YsPayConstant;
import com.ny.zmb.openapi.ysutil.from.JsPayReqCommand;
import com.ny.zmb.openapi.ysutil.from.JsPayRespCommand;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * 银盛支付
 */
@CrossOrigin
@RequestMapping("/ys/pay")
@RestController
@Slf4j
public class YsPayController extends EYinShengBase {

    @Resource
    private YsHttpUtil ysHttpUtil;
    @Resource
    private PmProductOrderMapper pmProductOrderMapper;

    /**
     * 收银台支付
     * @param orderNo
     * @return
     */
    @RequestMapping("cashierPay")
    public Result cashierPay(String orderNo,String payModel){
        if (StringUtil.isBlank(orderNo) || StringUtil.isBlank(payModel)){
            return Result.fail("参数有误");
        }
        QueryWrapper<PmProductOrder> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("order_no", orderNo);
        PmProductOrder productOrder = pmProductOrderMapper.selectOne(queryWrapper);
        if (null == productOrder || "1".equals(productOrder.getPayStatus()) || "1".equals(productOrder.getStatus())){
            return Result.fail("订单已支付");
        }
       if ("0".equals(productOrder.getPayStatus())){
            Integer create_time = productOrder.getCreateTime();
            Long newTime = System.currentTimeMillis() / 1000;
            Integer newIntTime = newTime.intValue();
            create_time = create_time + 60 * 30;
            if (newIntTime > create_time){
                return Result.fail("订单已关闭");
            }
        }
        JsPayReqCommand command = new JsPayReqCommand();
        command.setRequestNo(orderNo);
        command.setPayeeMerchantNo(SRC_MERCHANT_NO);
        command.setOrderDesc("商品购买");
        command.setAmount(productOrder.getAmount());
        command.setPayMode(payModel);
        command.setIsDivision("Y");
        command.setTimeOut("30");
        command.setNotifyUrl("https://tt.zhaimobao.com/test" + "/ys/pay/notify");
        JSONObject send = ysHttpUtil.send(ServiceEnum.cashierPay, YsPayConstant.ENV_PRD,
                MERCHANT_PRX, MERCHANT_PRX_PWD,ServiceEnum.cashierPay.getApiName(), command);
        return Result.ok(send.getJSONObject("bizResponseJson"));
    }
    /**
     * 支付-js
     * @return
     */
    @RequestMapping("jsPay")
    public Result jsPay(String orderNo,String wxOpenId,String alipayId){
        try {
            JsPayReqCommand command = new JsPayReqCommand();
            if (StringUtil.isBlank(orderNo)) {
                return Result.fail("订单编号不能为空");
            }
            QueryWrapper<PmProductOrder> queryWrapper = new QueryWrapper<>();
            queryWrapper.eq("order_no", orderNo);
            PmProductOrder productOrder = pmProductOrderMapper.selectOne(queryWrapper);
            if (null == productOrder || "1".equals(productOrder.getPayStatus()) || "1".equals(productOrder.getStatus())){
                return Result.fail("订单已支付");
            }
            command.setRequestNo(orderNo);
            command.setPayeeMerchantNo(SRC_MERCHANT_NO);
            command.setOrderDesc("商品购买");
            command.setAmount(productOrder.getAmount());
//            if (PHPConstant.WX_bankType.equals(productOrder.getBank_type())){
                command.setBankType(PHPConstant.WX_bankType);
                command.setPayMode(PHPConstant.WX_payModel);
                command.setWxAppId(PHPConstant.APPID);
                command.setWxOpenId(wxOpenId);
//            }
            if (PHPConstant.ALI_bankType.equals(productOrder.getBankType())){
                command.setBankType(PHPConstant.ALI_bankType);
                command.setPayMode(PHPConstant.ALI_payMode);
                command.setAlipayId(alipayId);
            }
            command.setNotifyUrl(PHPConstant.JAVA_BASE_URL + "/ys/pay/notify");
            JSONObject send = ysHttpUtil.send(ServiceEnum.JS_PAY, YsPayConstant.ENV_PRD,
                    MERCHANT_PRX, MERCHANT_PRX_PWD,ServiceEnum.JS_PAY.getApiName(), command);
            return Result.ok(send.getJSONObject("bizResponseJson"));
        }catch (Exception var){
            return Result.fail(var.getMessage());
        }
    }

    /**
     * 支付回调
     * @param response
     * @param request
     * @return
     */
    @RequestMapping(value = "notify",consumes = "application/x-www-form-urlencoded")
    public String payNotify(HttpServletResponse response, HttpServletRequest request){
        try {
            String requestId = request.getParameter("requestId");
            String version = request.getParameter("version");
            String charset = request.getParameter("charset");
            String signType = request.getParameter("signType");
            String sign = request.getParameter("sign");
            String serviceNo = request.getParameter("serviceNo");
            String bizResponseJson = request.getParameter("bizResponseJson");

            log.info(requestId);
            log.info(version);
            log.info(signType);
            log.info(charset);
            log.info(sign);
            log.info(serviceNo);
            log.info(JSONObject.toJSONString(bizResponseJson));
            bizResponseJson = bizResponseJson.replaceAll("\\\\","");
            JsPayRespCommand jsPayRespCommand = JSONObject.parseObject(bizResponseJson, JsPayRespCommand.class);
            String state = jsPayRespCommand.getState();
            // 处理订单信息
            if ("SUCCESS".equals(state)){
                QueryWrapper<PmProductOrder> queryWrapper = new QueryWrapper<>();
                queryWrapper.eq("order_no", jsPayRespCommand.getRequestNo());
                PmProductOrder pmProductOrder = this.pmProductOrderMapper.selectOne(queryWrapper);
                if ("1".equals(pmProductOrder.getPayStatus())){
                    return "success";
                }
                PmProductOrder pmProductOrders = new PmProductOrder();
                pmProductOrders.setPayStatus("1");
                pmProductOrders.setStatus("1");
                Long time = System.currentTimeMillis() / 1000;
                pmProductOrders.setPayTime(time.intValue());
                pmProductOrders.setShopDate(pmProductOrders.getPayTime().toString());
                pmProductOrderMapper.update(pmProductOrders,queryWrapper);
                try {
                    String result = HttpClient.get(PHPConstant.BASE_URL + "/api/index/wxpayNotify?outOrderNo="+ pmProductOrder.getOrderNo()).execute().asString();
                }catch (Exception var){
                    log.error("调用php代码失败->[{}]",pmProductOrder.getOrderNo());
                    throw  var;
                }
                return "success";
            }
            return "success";
        }catch (Exception var){
            return "success";
        }
    }
}
